package main

import(
	"fmt"
	"net/http"
	//"strconv"
	"time"
	"gopkg.in/gcfg.v1"
	"github.com/go-redis/redis"
	"github.com/gohouse/gorose"        //import Gorose
	_ "github.com/go-sql-driver/mysql" //import DB driver
	"github.com/gin-gonic/gin"
	log "github.com/jeanphorn/log4go"
)

// 全局变量
var Config *Conf = new(Conf)
var Db *gorose.Database
var redisDb *redis.Client

var rev *Rev
var dbDao *DbDao

func WebHandler(c *gin.Context){
	c.HTML(http.StatusOK, "index.tpl",gin.H{
		"title": "发送body测试：参数=值 多个参数用换行隔开",
	})
	//fmt.Fprintln(w, "hello world")
}


func main() {
	fmt.Println("启动")
	log.LoadConfiguration("config/log.json")

	// original log4go test
	log.Info("日志启动")


	defer log.Close()

	log.Info("读取配置")
	err := gcfg.ReadFileInto(Config, "config/conf.ini")
	if err != nil{
		log.Error("读取配置错误", err)
	}
	var DbConfig map[string]interface{}
	Config.InitDb(&DbConfig)
	log.Info("链接数据库")
	DbConn, dbErr := gorose.Open(DbConfig)
	if dbErr != nil{
		log.Error("链接数据库错误", DbConfig, dbErr)
	}
	defer DbConn.Close()
	Db = DbConn.NewDB()
	//res, rErr := Db.Table("bc_User").First()
	//if rErr != nil {
	//	log.Error(rErr)
	//	return
	//}
	//fmt.Println(Db.LastSql)
	//fmt.Println(res)
	log.Info("链接redis")
	redisDb = redis.NewClient(&redis.Options{
		Addr:     Config.Redis.Host + ":" + Config.Redis.Port,
		Password: Config.Redis.Password, // no password set
		DB:       Config.Redis.Database,  // use default DB
	})
	defer redisDb.Close()
	pong, err := redisDb.Ping().Result()
	
	log.Info(pong, err)
	rev = &Rev{C: make(chan RevMsg), Pipe:redisDb.Pipeline()}
	go rev.start()
	dbDao = &DbDao{}
	Port := "7011"
	log.Info("监听" + Port + "，开启web")
	router := gin.Default()
	//rev.QueryOnline2("A0096809", 2)
	gin.SetMode(gin.ReleaseMode)
	//gin.DefaultWriter = log.FileLogWriter
	router.LoadHTMLGlob("tpl/*")
	//router.POST("/events", events)
	router.GET("/log", WebHandler)
	//fmt.Println("1监听" + Port + "，开启web")
	router.POST("/log/write/online", rev.Online)
	//fmt.Println("2监听" + Port + "，开启web")
	router.POST("/log/write/update", rev.Update)
	router.POST("/log/write/offline", rev.Offline)
	router.POST("/log/write/delall", rev.Delall)
	router.POST("/log/write/checkonline", rev.Checkonline)
	router.POST("/log/query/online", rev.QueryOnline)
	router.Run(":" + Port)
}

func test(){
	

	t1 := time.Now()
	//redisDb.Set("p_" + strconv.Itoa(1), "p" + strconv.Itoa(1), 0).Err()()
	//for i := 0; i < 100000; i++ {
	//	redisDb.Set("p_" + strconv.Itoa(i), "p" + strconv.Itoa(i), 0)
	//}

	elapsed := time.Since(t1)
	fmt.Println("App elapsed: ", elapsed)
	keyRes1, kErr1 := redisDb.Get("p_").Result()
    fmt.Println("App elapsed: ", len(keyRes1), kErr1)

}
 

